package com.atguigu.gmall.mq.receiver;


import com.atguigu.gmall.mq.config.DeadLetterMqConfig;
import com.atguigu.gmall.mq.config.DelayMqConfig;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

/**
 *  1:接收MQ消息  同一个消息 接收二次   接收第一次时出现异常 可不应答 将消息放回队列  这样队列会把消息作为二次投递
 *  第二次投递时 如果还是抛出异常 可判断是否是第二次 如果是第二次 可选择拒绝 因为长时间不处理此消息、会
 *  造成消息在队列中堵塞 积压
 *
 *
 *
 */
@Configuration
public class ConfirmReceiver {

    @RabbitListener(bindings = @QueueBinding(
      value = @Queue(value = "queue.confirm",durable = "true",autoDelete = "false"),
      exchange = @Exchange(value = "exchange.confirm",durable = "true",autoDelete = "false"),
      key = "routing.confirm"
    ))
    public void receiverMessage(Message message, Channel channel) throws IOException {
        try {
            System.out.println("接收到的消息:" + new String(message.getBody()));
            //int i = 1/0;
            //channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            //e.printStackTrace();
            System.out.println("抛出异常");
            //是否为再投递
            System.out.println("是否是第二次投递：" + message.getMessageProperties().isRedelivered());
            if(message.getMessageProperties().isRedelivered()){
                System.out.println("拒绝投递");
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
            }else{
                System.out.println("未应答：消息重新进入队列、不批量处理");
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),true,true);
            }
        }
    }


    //接收死信
    @RabbitListener(queues = DeadLetterMqConfig.queue_dead_2)
    public void deadLetterMessage(String id,Message message,Channel channel){
        try {
            System.out.println("死信接收的消息：" + id);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
    //接收延迟
    @RabbitListener(queues = DelayMqConfig.queue_delay_1)
    public void delayedMessage(Message message,Channel channel) throws IOException {
        System.out.println("延迟消息：" + new String(message.getBody()));
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}
